package com.knirirr.beecountclassic;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout;
import android.text.format.Time;
import android.database.DatabaseUtils;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.graphics.drawable.Drawable;
import java.io.File;

public class NewprojActivity extends Activity implements OnClickListener
{
  static final String TAG = "BeeCountNew";

  DbHelper dbHelper;
  SQLiteDatabase db;
  Button newprojSaveButton;
  Button addNewCountButton;
  Button clearCountButton;
  EditText newprojName;
  TextView labelNewproj;
  String cockup;
  String totalfail;
  String duplicate;
  ArrayList<String> countNames;
  ViewGroup layout;
  Typeface font;
  int newBox;
  private ArrayList<EditText> myTexts;
  ActionBar actionBar;
  SharedPreferences prefs;


  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    if (android.os.Build.VERSION.SDK_INT < 11)
    {
      setTheme(android.R.style.Theme_NoTitleBar);
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newproj);
    Log.i(TAG, "New Project");

    myTexts = new ArrayList<EditText>();
    countNames = new ArrayList<String>();
    newprojSaveButton = (Button) findViewById(R.id.newprojSaveButton);
    addNewCountButton = (Button) findViewById(R.id.addNewCountButton);
    clearCountButton = (Button) findViewById(R.id.clearCountButton);
    newprojName = (EditText) findViewById(R.id.newprojName);
    newprojName.setHint(getString(R.string.newProjHint));
    layout = (ViewGroup) findViewById(R.id.newCountLayout);
    cockup = this.getString(R.string.emptyBox);
    totalfail = this.getString(R.string.noCounts);
    duplicate = this.getString(R.string.duplicate);
    newBox = 1;

    // background
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String backgroundPref = prefs.getString("pref_back", "default");
    Boolean fontPref = prefs.getBoolean("pref_font", true);
    String pictPref = prefs.getString("imagePath", "");

    LinearLayout layout = (LinearLayout) findViewById(R.id.newprojScreen);
    if (backgroundPref.equals("none"))
    {
       // boring black screen
    }
    else if (backgroundPref.equals("custom"))
    {
      if (!(pictPref.equals(""))) 
      {
        if (new File(pictPref).isFile())
        {
          Drawable background = Drawable.createFromPath(pictPref);
          layout.setBackgroundDrawable(background);
        }
        else
        {
          Toast.makeText(this,getString(R.string.customMissing),Toast.LENGTH_SHORT).show();
          layout.setBackgroundResource(R.drawable.beecount_knitting);
        }
      }
      else
      {
        Toast.makeText(this,getString(R.string.customNotDefined),Toast.LENGTH_SHORT).show();
        layout.setBackgroundResource(R.drawable.beecount_knitting);
      }
    }
    else if (backgroundPref.equals("default"))
    {
      layout.setBackgroundResource(R.drawable.beecount_knitting);
    } 


    // fancy font

    newprojSaveButton.setOnClickListener(this);
    addNewCountButton.setOnClickListener(this);
    clearCountButton.setOnClickListener(this);
    labelNewproj = (TextView)  findViewById(R.id.labelNewproj);
    labelNewproj.setText(R.string.labelNewproj);

    if (fontPref == true)
    {
      font = Typeface.createFromAsset(getAssets(), "village.ttf"); 
      newprojSaveButton.setTypeface(font);
      addNewCountButton.setTypeface(font);
      clearCountButton.setTypeface(font);
      labelNewproj.setTypeface(font);
    }

  }

  public void onClick(View view)
  {
    switch (view.getId())
    {
      case R.id.newprojSaveButton:
        // stuff
        saveProject();
        break;
      case R.id.addNewCountButton:
        // stuff
        newCount();
        break;
      case R.id.clearCountButton:
        clearCount();
        break;
    }
  }

  @Override
  @TargetApi(14)
  public boolean onCreateOptionsMenu(Menu menu)                                                                         
  {                                                                                                                     
    MenuInflater inflater = getMenuInflater();                                                                          
    inflater.inflate(R.menu.newprojmenu, menu);                                                                                
    if (android.os.Build.VERSION.SDK_INT > 13)
    {
      actionBar = getActionBar();                                                                                         
      actionBar.setHomeButtonEnabled(true);                                                                               
    }
    return true;                                                                                                        
  }  

  public boolean onOptionsItemSelected(MenuItem item)
  {
    switch (item.getItemId())
    {
      case R.id.listProj:
        startActivity(new Intent(this, ListprojActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        break;
      case android.R.id.home:
        startActivity(new Intent(this, WelcomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        break;
      default:
        return super.onOptionsItemSelected(item);
    }
    return true;
  }

  private void newCount()
  {
    // attempt to add a new EditText to an array thereof
    //Log.i(TAG,"Adding new count!");
    EditText c = new EditText(this);
    c.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    c.setHint(this.getString(R.string.boxFill) + " " + newBox);
    //c.setText(this.getString(R.string.boxFill) + " " + newBox);
    layout.addView(c);
    myTexts.add(c);
    newBox++;
  }

  private void clearCount()
  {
    if (myTexts.isEmpty())
      return;
    int count_number = myTexts.size();
    ViewGroup layout = (ViewGroup) findViewById(R.id.newCountLayout);
    layout.removeView(myTexts.get(count_number -1));   
    myTexts.remove(count_number -1);
    newBox--;
  }


  private void saveProject()
  {

    // first, the project name
    String proj_name = newprojName.getText().toString();
    String count_name;

    if (myTexts.isEmpty())
    {
      Toast.makeText(this,totalfail,Toast.LENGTH_SHORT).show();          
      return;
    }

    // check that the boxes are filled in
    int carryon = 1;
    if (StringUtils.isBlank(proj_name))
    {
      carryon = 0;
    }
    for (EditText c : myTexts)
    {
      count_name = c.getText().toString();
      if (StringUtils.isBlank(count_name))
      {
        carryon = 0;
        break;
      }
    }
    if (carryon == 0)
    {
      Toast.makeText(this,cockup,Toast.LENGTH_SHORT).show();     
      return;
    }

    // check for unique names
    countNames.clear();
    for (EditText c : myTexts)
    {
      count_name = c.getText().toString();
      if (countNames.contains(count_name))
      {
        Toast.makeText(this,duplicate,Toast.LENGTH_SHORT).show();     
        return;
      }
      else
      {
        countNames.add(count_name);
      }
    }


    // get a database connection
    dbHelper = new DbHelper(this);
    db = dbHelper.getWritableDatabase();

    /* 
     * get various bits of text into the database
     */


    // save it, and the get its ID for use in assigning to 
    // the counts
    Log.i(TAG,"NAME: " + proj_name);
    Time now = new Time();
    now.setToNow();
    ContentValues values = new ContentValues();
    //long timestamp = System.currentTimeMillis()/1000;
    long timestamp = System.currentTimeMillis();
    values.put(DbHelper.P_CREATED_AT,timestamp);
    values.put(DbHelper.P_NAME,DatabaseUtils.sqlEscapeString(proj_name.replaceAll("_","-")));
    long last_id = db.insertOrThrow(DbHelper.PROJ_TABLE,null,values);
    String last_id_string = String.valueOf(last_id);

    // text values from each of the counts
    for (EditText c : myTexts)
    {
      values.clear();
      count_name = c.getText().toString();
      values.put(DbHelper.C_PROJECT_ID,last_id);
      values.put(DbHelper.C_NAME,count_name.replaceAll("_","-").replaceAll("'","\'"));
      //values.put(DbHelper.C_NAME,DatabaseUtils.sqlEscapeString(count_name.replaceAll("_","-")));
      //values.put(DbHelper.C_NAME,count_name.replaceAll("_","-"));
      values.put(DbHelper.C_COUNT,0);
      db.insertOrThrow(DbHelper.COUNT_TABLE,null,values);
      Log.i(TAG,"COUNT: " + count_name + "," + last_id_string);
    }

    // close db, of course
    db.close();

    // Huzzah!
    Toast.makeText(this,"Project saved!",Toast.LENGTH_SHORT).show();
    //startActivity(new Intent(this, WelcomeActivity.class)); // later, go directly to a view
    finish();
  }

  // check for duplicates of counts
  // http://stackoverflow.com/questions/562894/java-detect-duplicates-in-arraylist
  public static <T> boolean hasDuplicate(Collection<T> list) 
  {
    Set<T> set = new HashSet<T>();
    // Set#add returns false if the set does not change, which
    // indicates that a duplicate element has been added.
    for (T each: list) if (!set.add(each)) return true;
    return false;
  }
}
  
